#include <iostream>
#include <string>
#include <memory>
#include <sstream>
#include <jsoncpp/json/json.h>

bool serialize(const Json::Value& root, std::string& body)
{
    //先实例化一个工厂类对象
    Json::StreamWriterBuilder writer_builder;

    // 配置StreamWriterBuilder，使其不进行Unicode转义
    writer_builder.settings_["emitUTF8"] = true;
    
    //再用工厂类对象生产派生类对象
    std::unique_ptr<Json::StreamWriter> writer(writer_builder.newStreamWriter());

    std::stringstream ss;

    int ret = writer->write(root, &ss);   //将生成的Json字符串输出到ss字符串流中
    if (ret != 0)
    {
        perror("serialize");
        return false;
    }

    body = ss.str();
    return true;
}

bool unserialize(const std::string& body, Json::Value& root)
{
    //实例化一个工厂类
    Json::CharReaderBuilder reader_builder;

    //用工厂类生产一个对象
    std::unique_ptr<Json::CharReader> reader(reader_builder.newCharReader());

    //将反序列化的结果存入root中
    bool ret = reader->parse(body.c_str(), body.c_str() + body.size(), &root, nullptr);
    if (ret == false)
    {
        perror("unserialize");
        return false;
    }
    return true;
}

int main()
{
    Json::Value student;
    std::string name = "张三";
    int age = 20;
    float score[] = {91.2, 84.8, 99.0};

    student["姓名"] = name;
    student["年龄"] = age;
    student["成绩"].append(score[0]);
    student["成绩"].append(score[1]);
    student["成绩"].append(score[2]);

    Json::Value fav;
    fav["书籍"] = "西游记";
    fav["运动"] = "羽毛球";

    student["爱好"] = fav;

    std::string body;
    serialize(student, body);
    std::cout << body << std::endl;

    Json::Value root;
    unserialize(body, root);

    Json::Value fav_bak = root["爱好"];
    int size = root["成绩"].size();
    std::cout << size << std::endl;
    std::cout << root["姓名"].asString() << std::endl;
    std::cout << root["年龄"].asInt() << std::endl;
    for (int i = 0; i < size; i++)
        std::cout << root["成绩"][i].asFloat() << std::endl;
    std::cout << fav_bak["书籍"].asString() << std::endl;
    std::cout << fav_bak["运动"].asString() << std::endl;

    return 0;
}

